<template>
	<uv-navbar
	  :fixed="false"
	  :title="title"
	  left-arrow
	  @leftClick="$onClickLeft"
	/>
	<view style="overflow:hidden;background:#fff;">
		<view class="set-box bg-white">
			<uv-alert  type="warning" v-if="form.checkStatus == 1" description="回款正在审核中,不可以修改!"></uv-alert>
			<uv-alert  type="warning" v-else-if="form.checkStatus == 2" description="回款已经审核通过,不可以修改!"></uv-alert>
			<uv-alert  type="warning" v-else-if="form.checkStatus == 3" description="审核不通过，不可修改数据，请重新添加订单!"></uv-alert>
			<uv-form :model="form" ref="uForm" :errorType="errorType" labelWidth="85" :rules="rules">
				<uv-form-item required label="回款编号:"  prop="number">
					<uv-input v-model="form.number" :disabled="isCheck"  />
				</uv-form-item>
				<uv-form-item  label="选择客户:" @click="type != 'check' ? selectShow() : ''"  required >
					<uv-input disabledColor="#ffffff" disabled v-model="form.customerName" placeholder="选择客户" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item  label="选择订单:" @click="type != 'check'  ? selectShow4() : ''"  required>
					<uv-input disabledColor="#ffffff" disabled v-model="form.contractName" placeholder="选择订单" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item  label="收款方式:" :disabled="isCheck" required>
					<uv-radio-group v-model="form.payType">
						<uv-radio  :name="1" label="默认方式"></uv-radio>
						<uv-radio  :name="2" label="线上收款"></uv-radio>
					</uv-radio-group>
				</uv-form-item>
				<uv-form-item label="回款金额:" prop="money" required >
					<uv-input type="number" v-model="form.money" :disabled="isCheck"  />
				</uv-form-item>
				<uv-form-item v-if="form.payType == 1"  label="回款日期 :" @click="type != 'check'  ? createTimeShow() : ''">
					<uv-input  v-model="returnTime" placeholder="选择回款日期 " disabled disabledColor="#ffffff" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item v-if="form.payType == 1"   label="回款账户:" @click="type != 'check'  ? selectShow3() : ''"  required >
					<uv-input disabledColor="#ffffff" disabled v-model="form.accountName" placeholder="选择回款账户" >
						<template v-slot:suffix>
							<uv-icon name="arrow-right"></uv-icon>
						</template>
					</uv-input>
				</uv-form-item>
				<uv-form-item label="支付流水号:" required prop="payTransactionRecord" >
					<uv-input disabledColor="#ffffff" v-model="form.payTransactionRecord" placeholder="请输入支付流水号" />
				</uv-form-item>
				
				<!-- <uv-form-item  label="审批人:" >
					<uv-input disabledColor="#ffffff" disabled v-model="form.flowAdminIdName" placeholder="请去审批流程里配置订单审批" />
				</uv-form-item> -->
				<uv-form-item label="备注:" >
					<uv-textarea v-model="form.remark" :disabled="isCheck" placeholder="请输入备注"></uv-textarea>
				</uv-form-item>
				<uv-form-item  label="审批流程" labelPosition="top" labelWidth="80">
					<flow-step :flowAdmins="flowAdmins" />
				</uv-form-item>
			</uv-form>
			<view class="mt-4 flex pl-10 pr-10" style="text-align: center;" v-if="!isCheck">
				<uv-button class="flex-fill mr-10" color="#09b4f1" @click="submit(1)" :disabled="form.checkStatus == 1 || form.checkStatus == 2 || form.checkStatus == 3" v-if="!form.status||form.status&&form.status<2" :ripple="true">暂存</uv-button>
				<uv-button class="flex-fill ml-10" color="#09b4f1" @click="submit(2)" :disabled="form.checkStatus == 1 || form.checkStatus == 2 || form.checkStatus == 3" v-if="!form.status||form.status&&form.status<2" :ripple="true">确定提交</uv-button>
			</view>
		</view>
		<!-- 选择客户弹窗 -->
		<uv-popup  mode="bottom" round="38"  ref="selectShowRef" >
			<view class="popup-content">
				<view class="popup-title">
					<view class=""  style="width: 45px;">
					</view>
					<text class="">选择客户</text> 
					<view class="" @click="selectShowClose" style="width: 45px;">
						<uv-icon name="close"  color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<uv-search margin="30rpx 20rpx" shape="square" v-model="keyword" :show-action="false" :clearabled="true"  placeholder="输入客户名称搜索" @change="onSearch"></uv-search>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;" @scrolltolower="reachBottom">
					<view class="list">
						<block v-if="customerList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in customerList" :key="index" @click="onItem(item,index)">
									<view class="title">{{item.name}}</view>
									<view class="check-icon">
										<uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
									</view>
								</view>
							</view>
							<uv-load-more :status="listStatus" ></uv-load-more>
						</block>
						<uv-empty text="暂无数据" v-else  mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-popup  mode="bottom" round="38"  ref="selectShowRef4" >
			<view class="popup-content">
				<view class="popup-title">
					<view class=""  style="width: 45px;">
					</view>
					<text class="">选择订单</text> 
					<view class="" @click="selectShowClose4" style="width: 45px;">
						<uv-icon name="close"  color="#909399" size="30"></uv-icon>
					</view>
				</view>
				<scroll-view scroll-y style="height: 760rpx;width: 100%;" @scrolltolower="reachBottom3">
					<view class="list">
						<block v-if="businessList.length > 0">
							<view class="mb-4">
								<view class="item flex" v-for="(item,index) in businessList" :key="index" @click="onItem4(item,index)">
									<view class="title">{{item.name}}</view>
									<view class="check-icon">
										<uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
									</view>
								</view>
							</view>
						</block>
						<uv-empty text="暂无数据" v-else  mode="list"></uv-empty>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
		<uv-action-sheet :actions="accountList" ref="selectShowRef3" title="请选择回款账户" @select="accountClick"></uv-action-sheet>
		<uv-datetime-picker ref="datetimePicker" v-model="timeValue" mode="date" @confirm="createTimeChange"></uv-datetime-picker>
		<!-- <uv-calendar ref="datetimePicker" v-model="timeValue" :defaultDate="new Date()" :start="minDate" :end="maxDate" @confirm="createTimeChange"></uv-calendar> -->
	</view>
</template>

<script setup>
import {
  ref,
  unref,
  computed
} from 'vue'
import { onLoad,onShow } from '@dcloudio/uni-app'
import {
  getCustomerListPage,
  getDictData
} from '@/api/customer'
import {
  getContractPage,getMyOrderList
} from '@/api/contract'
import {
  getCode,
  receivablesCreate,
  getReceivables,
  receivablesUpdate,
  check,
  pay
} from '@/api/receivables'
import {
  getSimpleUserList,
  getFlowUsers,
  getSimpleUserList2
} from '@/api/user'
import AddressSelect from '@/components/AddressSelect/index.vue'
import { formatDateTime,prePage } from '@/utils/util'
const minDate  = '2020/01/01'
const maxDate  = '2030/12/31'
const title = ref('添加回款')
const labelPosition = ref('left')
const keyword = ref('')
const listStatus =ref('loadmore')
const listStatus3 =ref('loadmore')
const customerList = ref([])
const accountName  = ref('')
const page = ref(1)
const page3 = ref(1)
const pageSize = ref(10)
const lastPage = ref(false)
const lastPage3 = ref(false)
const selectList = ref([])
const businessData = ref({})
const type = ref('add')
const contractId = ref(0)
const customerId = ref(0)
const nextTime = ref('')
const returnTime  = ref(formatDateTime(new Date()))
const content = ref('')
const customerName = ref('')
const form = ref({
	customerId: '',
	customerName: '',
	contractName: '',
	returnTime: (new Date()).getTime(),
	accountName: '',
	money: '',
	remark: '',
	discountRate: '',
	totalPrice: '',
	contactsName: '',
	orderAdminName: '',
	payType: 1
})
const timeText = ref('')
const errorType = ref('message')
const rules = ref({

})
const customerContacts = ref([])
const userList = ref([])
const username = ref('')
const keyword3 = ref('')
const businessList = ref([])
const isCheck = ref(false)
const form2 = ref({
	id: 0,
	agreeType: 1,
	remark: ''
})
const accountList = ref([])
const flowAdmins = ref([])

onLoad((e) => {
	if(e.type){
		type.value = e.type
	}
	if(type.value == 'check'){
		isCheck.value = true
		title.value = '审核回款'
		contractId.value = e.id
		getContractInfo()
	}
	if(type.value == "edit") {
		title.value = '编辑回款'
		contractId.value = e.id
		getContractInfo()
	}else{
		getNumber()
	}
	getCustomerList()
	getUserList()
	getFlowUsersList()
	getBusiness()
	
})

onShow(()=>{

})
const getBusiness = async()=>{
let data2 = await getMyOrderList()
	businessList.value = data2
}
const getFlowUsersList = async() => {
	flowAdmins.value = await getFlowUsers({flowType: 'receivables',id:contractId.value})
	let flowAdminsId = "";
	flowAdmins.value.forEach(item => {
	  if(flowAdminsId == ''){
		flowAdminsId = item.adminIds
	  }else{
		flowAdminsId = flowAdminsId + ',' + item.adminIds
	  }
	})

	form.value.flowAdminId = flowAdminsId

	
}

const getNumber = async() => {
	form.value.number = await getCode()
}

const selectShowRef = ref()
const selectShow = () => {
	unref(selectShowRef).open()
}
const selectShowClose = () => {
	unref(selectShowRef).close()
}

const datetimePicker = ref()
const createTimeShow = () => {
	unref(datetimePicker).open()
}

// 选择时间
const createTimeChange = (e) => {
	form.value.returnTime = e.value
	returnTime.value = formatDateTime(e.value)
}


// 获取商机数据详情
const getContractInfo = async() => {
	form.value = await getReceivables({id:contractId.value})
	returnTime.value = formatDateTime(form.value.returnTime)
	var accounts = await getDictData({type:'payee_type'})
	accounts.forEach(item => {
	  if(item.value == (form.value.accountId+"")){
		form.value.accountName = item.name
	  }
	})
	
}
// 搜索
const onSearch = () => {
	page.value = 1
	lastPage.value = false
	getCustomerList()
}


const getCustomerList = async(isNextPage,pages) => {
	await getCustomerListPage({
		pageNo: page.value,
		pageSize: pageSize.value,
		relation: 'my',
		name:keyword.value,
	}).then(res => {
		if(res) {
			// 不够一页
			if (res.list.length < 10) {
				listStatus.value = 'nomore'
			}
			// 最后一页
			if(res.list.length == 0) {
				lastPage.value = true
			} 
			// 第二页开始
			if(isNextPage) {
				customerList.value = customerList.value.concat(res.list)
				return 
			}
			customerList.value = res.list
			
			if(form.value.customerId) {
				customerList.value.forEach((item,index) => {
					if(form.value.customerId == item.id) {
						item.checked = true
						customerName.value = item.name
					} else {
						item.checked = false
					}
				})
			}
		}
	})
}

const getUserList = async() => {
	accountList.value = await getDictData({type:'payee_type'})

}


// 滚动到底部加载更多
const reachBottom = () => {
	if(lastPage.value || listStatus.value == 'loading') return 
	listStatus .value= 'loading'
	setTimeout(() => {
		getCustomerList(true,++page.value)
		if(customerList.value.length >= 10) {
			listStatus.value = 'loadmore';
		}else{
			listStatus.values = 'loading';
		} 
	}, 1200)
}

const reachBottom3 = () => {
	if(lastPage3.value || listStatus3.value == 'loading') return 
	listStatus3 .value= 'loading'
	setTimeout(() => {
		getUserList(true,++page3.value)
		if(userList.value.length >= 10) {
			listStatus3.value = 'loadmore';
		}else{
			listStatus3.values = 'loading';
		} 
	}, 1200)
}
// 选择客户
const onItem = async(val,i) => {
	customerList.value.forEach((item,index) => {
		if(val.id == item.id) {
			item.checked = true
			val.name=val.name?val.name:item.name;
		} else {
			item.checked = false
		}
	})
	form.value.customerId = val.id
	//customerId.value = val.id
	form.value.customerName = val.name ? val.name : ''
	//根据客户查找商机
	// let data2 = await getContractPage({customerId:val.id})
	
	selectShowClose()
}


const selectShowRef3 = ref()
const selectShow3 = async() => {
	unref(selectShowRef3).open()
}
const selectShowClose3 = () => {
	unref(selectShowRef3).close()
}

const accountClick = (index) => {
	form.value.accountName = index.name
	form.value.accountId = index.value
}


const selectShowRef4 = ref()
const selectShow4 = async() => {
	unref(selectShowRef4).open()
}
const selectShowClose4 = () => {
	unref(selectShowRef4).close()
}

const onItem4 = async(val,i) => {
	businessList.value.forEach((item,index) => {
		if(val.id == item.id) {
			item.checked = true
			val.name=val.name?val.name:item.name;
		} else {
			item.checked = false
		}
	})
	form.value.contractId = val.id
	//customerId.value = val.id
	form.value.contractName = val.name ? val.name : ''

	selectShowClose4()
}



// 提交跟进
const uForm = ref()
const submit = async(val) => {
	if(form.value.customerId == ''){
		uni.showToast({
			icon: 'error',
			title: '请选择客户'
		})
		
		return
	}
	
	if(form.value.contractName == ''){
		uni.showToast({
			icon: 'error',
			title: '请选择订单'
		})
		
		return
	}
	
	if(form.value.money == ''){
		uni.showToast({
			icon: 'error',
			title: '请填写收款金额'
		})
		
		return
	}
	
	if(form.value.payType == 1 && form.value.accountName == ''){
		uni.showToast({
			icon: 'error',
			title: '请选择收款账户'
		})
		
		return
	}else{
		form.value.accountId = 1
	}
	
	onSubmit()
	form.value.status = val;
	if(form.value.payType == 2){
		await pay({from:'',paytype:'weixin',uni:form.value.number})
	}
	

}


// 修确认提交
const onSubmit = async() => {
	if(type.value == 'add'){
		await receivablesCreate(form.value)
		uni.showToast({
			title: '添加成功',
			icon: 'success',
			duration: 2000
		})
		prePage().$vm.isRefresh = true
		setTimeout(() => {
			uni.navigateBack();
		}, 1000);
	}else{
		await receivablesUpdate(form.value)
		uni.showToast({
			title: '修改成功',
			icon: 'success',
			duration: 2000
		})
		prePage().$vm.isRefresh = true
		setTimeout(() => {
			uni.navigateBack();
		}, 1000);
	}
	
}
	
	
</script>

<style lang="scss" scoped>
.set-box {
  padding: 0rpx 22rpx;
  margin-bottom: 80rpx;
  .list {
		margin: 40rpx 15rpx 60rpx;
    .item {
			position: relative;
			border-radius: 15rpx;
			box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
			padding: 25rpx 35rpx;
			margin-bottom: 45rpx;
			.number {
				margin-bottom: 20rpx;
			}
			.content {
				margin-bottom: 20rpx;
				.price {
					width: 245rpx;
					font-size: 28rpx;
					color: #fa3534;
				}
			}
			.close {
				position: absolute;
				right: -8px;
				top: -30rpx;
				background-color: #fff;
				border-radius: 50%;
				height: 60rpx;
				width: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
			}
    }

  }
 }
 .popup-content {
	.popup-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
		font-size: 35rpx;
		font-weight: 600;
		text-align: center;
		height: 50px;
		padding-right: 25rpx;
	}
	.list {
		margin-bottom: 45rpx;
		.item {
			padding: 0 25rpx;
			justify-content: space-between;
			height: 45px;
			.title {
				flex: 1;
				font-size: 28rpx;
				font-weight: 600;
			}
			.check-icon {
				text-align: center;
				width: 100rpx;
			}
		}
	}
	.bottom_btn {
		display: flex;
		justify-content: flex-end;
		padding: 28rpx 10rpx 45rpx;
	}
}
</style>
